package com.web;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import com.domain.Member;

@Controller
public class MemberController {

	@Autowired
	protected RestTemplate restTemplate;

	@ResponseBody
	@RequestMapping(value = "/members", method = RequestMethod.GET)
	public Member getRestMembers() {
		// Return view membertemplate. Via resolver the view
		// will be mapped to a JAXB Marshler bound to the Member class
		Member member = new Member();
		member.setName("John Doe");
		member.setPhone("1-800-800-800");
		member.setEmail("john@doe.com");
		// model.addAttribute("member", member);

		restTemplate
				.getForObject(
						"http://search.yahooapis.com/NewsSearchService/V1/newsSearch?appid={appid}&query={query}&results={results}&language={language}",
						String.class, "YahooDemo", "sports", "2", "en");

		return member;
	}

	@ResponseBody
	@RequestMapping(value = "/call", method = RequestMethod.GET)
	public String callRest() {

		String s = restTemplate
				.getForObject(
						"http://gdata.youtube.com/feeds/api/standardfeeds/US/most_popular_Film?orderby=viewCount",
						String.class);

		return s;
	}

	@RequestMapping(value = "/update", method = RequestMethod.GET)
	public void testUpdate() {

		
		StringBuffer buffer = new StringBuffer();

		String result;
		String line;
		String response = "";

		try {
			java.net.URL url = new URL("http://localhost:8080/testweb/call");
			HttpURLConnection connection = (HttpURLConnection) url
					.openConnection();

			System.out.println("sending request...");
			connection.setRequestMethod("GET");
			connection.setDoOutput(false);
			Map headerFields = connection.getHeaderFields();
			System.out.println("header fields are: " + headerFields);

			int rspCode = connection.getResponseCode();
			System.out.println(rspCode);
			if (rspCode == 200) {

				BufferedReader rd = new BufferedReader(new InputStreamReader(
						connection.getInputStream()));
				while ((line = rd.readLine()) != null) {
					response += line;
				}
			}

			System.out.println("\n *INDEX RESPONSE XML * \n\n" + response
					+ "\n\n");

		} catch (Exception e) {
			System.out.println("Errors...");
		}

		// https://www.facebook.com/dialog/oauth?client_id=235800789822851&redirect_uri=https://www.facebook.com/connect/login_success.html&response_type=code

	}
}
